<template>
  <div v-show="showDialog && !detailInfo.visible" class="app-container-flex">
    <div class="width100">
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :clear-type="clearType"
          :slip-select-request="slipSelectRequest"
          :filter-btn="filterInfo.searchBtn"
        >
        </NewPageFilter>
        <el-button @click="closeDetailList">列表页</el-button>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList"> </NewPageFilter>
        <div class="display-flex">
          <Group-select
            :options="groupSelectInfo.options"
            v-model:selections="groupSelectInfo.selections"
            @callback="groupSelect"
            @callbackVal="updateGroupSelections"
          ></Group-select>
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        v-if="groupFlag"
        class="groupFlag-container"
        :is-group-search="true"
        v-model:data="groupSelectInfo.data"
        :field-list="tableInfo.fieldList"
        :check-box="false"
        :tab-index="false"
        :pager="false"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :span-method="arraySpanMethod"
        :row-class-name="tableRowClassName"
        @exChange="exChange"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-orderNo="scope">
          {{ scope.row.orderNo }}
        </template>
        <template v-slot:col-assetName="scope">
          {{ scope.row.assetName }}
        </template>
      </table-container>
      <table-container
        v-else
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :check-box="false"
        :tab-index="true"
        :field-list="tableInfo.fieldList"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
        @pageInfo="pageInfo"
      >
        <template v-slot:col-code="scope">
          <span
            v-if="$permission('pendWithTableKit:details')"
            class="slip-edit"
            @click="showDetail(scope.row)"
            >{{ scope.row.code || '-' }}</span
          >
          <span v-else>{{ scope.row.code || '-' }}</span>
        </template>
      </table-container>
    </div>
  </div>
  <set-preference
    v-if="preferenceInfo.visible"
    v-model:visible="preferenceInfo.visible"
    :search-list="filterInfo.searchList"
    :field-list="tableInfo.fieldList"
    :customize-user-v-o="filterInfo.query.customizeUserVO"
    @callback="setPreferenceCallback"
  />
  <advanced-search
    v-if="advancedSearchInfo.visible"
    v-model:visible="advancedSearchInfo.visible"
    :field-list="tableInfo.fieldList"
    v-model:form-data="advancedSearchInfo.data"
    @callback="advancedSearchCallback"
  />
  <order-detail
    v-if="detailInfo.visible"
    :id="detailInfo.id"
    v-model:visible="detailInfo.visible"
    @returnBack="getList"
  />
</template>
<script setup name="pendWithTableKit">
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import { ElMessage } from 'element-plus'
import {
  getWithTableKitDetailCheckAll,
  getWithTableKitDetailCheckGroup,
  getWithTableKitDetailCheckPage,
} from '@/api/withTable.js'

const { proxy } = getCurrentInstance()
const emit = defineEmits()

const TableContainer = defineAsyncComponent(() =>
  import('@/components/TableContainer/index')
)

const GroupSelect = defineAsyncComponent(() =>
  import('@/components/GroupSelect/index')
)
const SetPreference = defineAsyncComponent(() =>
  import('@/components/SetPreference/index')
)
const AdvancedSearch = defineAsyncComponent(() =>
  import('@/components/AdvancedSearch/index')
)
const OrderDetail = defineAsyncComponent(() => import('./details'))

const props = defineProps(['visible'])

//导出提示相关配置
const dialogInfo = reactive({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: true,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    // {
    //   label: '打印',
    //   type: 'primary',
    //   event: checkConfirm,
    //   show: true,
    // },
  ],
})
// 过滤相关配置
const groupSelectInfo = reactive({
  options: [],
  selections: [],
  data: [],
})
const filterInfo = reactive({
  sortArr: [],
  query: {
    groupMap: {},
    groups: [],
    sortString: '',
    queryMap: {
      deptAuth: {
        asTbName: 'with_table_kit_check',
        columnName: 'dept_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'deptAuth',
      },
      supplierAuth: {
        asTbName: 'with_table_kit_check',
        columnName: 'supplier_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'supplierAuth',
      },
    },
    customizeUserVO: {},
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [],
})

// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  data: [],
  selections: [],
  fieldList: [],
})
const detailListInfo = reactive({
  visible: false,
})
const preferenceInfo = reactive({
  visible: false,
})
const detailInfo = reactive({
  visible: false,
  id: '',
})
const advancedSearchInfo = reactive({
  visible: false,
  data: {},
})
let page = reactive({
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
const clearType = ref(true)
const groupFlag = ref(false)
const slipSelectRequest = ref(true)

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})

let obj = {
  checkStatusValue: {
    label: '状态',
    value: 'checkStatusValue',
    asValue: 'checkStatus',
    componentType: 'select-model',
    code: 'with_table_kit_check_status',
    show: false,
    hidden: true,
  },
  name: {
    label: '名称',
    value: 'name',
    componentType: 'input',
    show: false,
    hidden: true,
  },
  code: {
    label: '编码',
    value: 'code',
    componentType: 'input',
    type: 'slot',
    show: false,
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()

function pageInfo(obj) {
  page = obj
}
function handleClose() {
  dialogInfo.visible = false
}
function closeDetailList() {
  proxy.$store.dispatch('app/toggleOpenFilter')
  showDialog.value = false
  emit('callback')
}
function updateGroupSelections(arr) {
  filterInfo.query.groups = arr
  groupSelectInfo.selections = arr
  if (!arr.length) {
    filterInfo.query.groups = []
    filterInfo.query.groupMap = {}
    groupSelectInfo.data = []
    groupFlag.value = false
  }
}
function groupSelect(arr) {
  if (arr.length) {
    //点击分组
    groupFlag.value = true
    filterInfo.query.groups = arr
    groupSelectInfo.selections = arr
    getCustomizeGroupsList()
  } else {
    ElMessage.warning({
      message: '请选择分组条件！',
      showClose: true,
      duration: 3000,
    })
  }
}
async function getCustomizeGroupsList(len, param, expande) {
  //分组查询
  let params = {}
  if (len) {
    params = param
  } else {
    params = filterInfo.query
  }
  if (filterInfo.query.queryDtoList && filterInfo.query.queryDtoList.length) {
    params = proxy.$fn.deepClone(params)
    params.queryMap = {}
  }
  await getWithTableKitDetailCheckGroup(params).then(async (res) => {
    if (res && res.success) {
      let data = res.data
      let newData = []
      if (len) {
        await data.forEach((item, index) => {
          newData.push({
            ...item,
            id: index + Math.random(),
            isColspan: true,
            children: [{ ...item, id: index + Math.random(), isColspan: true }],
          })
        })
        expande.children = newData
      } else {
        await data.forEach((item, index) => {
          newData.push({
            ...item,
            id: index + Math.random(),
            isColspan: true,
            children: [{ id: index + Math.random(), isColspan: true }],
          })
        })
        groupSelectInfo.data = newData
      }
    }
  })
}
function exChange(data, expandedRows) {
  //展开分组
  if (expandedRows) {
    let len = data.nextGroups.length
    if (len) {
      let params = {
        ...filterInfo.query,
        groups: data.nextGroups,
        groupMap: { ...data.query },
        queryMap: { ...filterInfo.query.queryMap, ...data.query },
      }
      getCustomizeGroupsList(len, params, data)
    } else {
      let params = {
        ...filterInfo.query,
        groups: [],
        groupMap: {},
        queryMap: { ...filterInfo.query.queryMap, ...data.query },
      }
      getWithTableKitDetailCheckAll(params).then(async (res) => {
        if (res && res.success) {
          let resData = res.data
          await resData.forEach((item, index) => {
            item.id = index + Math.random()
            item.isColspan = false
          })
          data.children = resData
        }
      })
    }
  } else {
    data.children = [{ id: Math.random(), isColspan: true }]
  }
}
function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.visible = true
}
async function advancedSearchCallback(obj) {
  let arr = [
    {
      asTbName: 'with_table_kit_check',
      columnName: 'dept_id',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'deptAuth',
    },
    {
      asTbName: 'with_table_kit_check',
      columnName: 'supplier_id',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'supplierAuth',
    },
  ]
  filterInfo.query.queryMap = {}
  filterInfo.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.data = obj.data
  if ((await groupSelectInfo.selections.length) > 0) {
    await getCustomizeGroupsList()
  } else {
    groupSelectInfo.data = []
    await getList()
  }
  clearType.value = !clearType.value
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
}
// 获取列表
async function getList() {
  tableInfo.refresh = Math.random()
}
// 搜索
function search() {
  advancedSearchInfo.data = {}
  filterInfo.query.queryDtoList = []
  if (groupSelectInfo.selections.length > 0) {
    getCustomizeGroupsList()
  } else {
    groupSelectInfo.data = []
    tableInfo.initCurpage = Math.random()
    tableInfo.refresh = Math.random()
  }
}
function showDetail(row) {
  detailInfo.id = row.orderId
  detailInfo.visible = true
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.data = {}
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'withTableKitCheckDetailList-com.slip.spd.entity.vo.withtable.WithTableKitDetailCheckVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.searchList,
        data.detail
      )
      let tableFieldInfo = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail,
        true
      )
      tableInfo.fieldList = tableFieldInfo.fieldList
      groupSelectInfo.options = tableFieldInfo.groupOption
      filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.query.queryMap,
      }
      filterInfo.searchList = searchInfo.searchList
      filterInfo.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.copyQueryMap = proxy.$fn.deepClone(filterInfo.query.queryMap)
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.api = getWithTableKitDetailCheckPage
      getList()
    }
  })
}
function sortChange(column) {
  if (filterInfo.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.sortArr)
    filterInfo.sortArr = arr
    filterInfo.query.sortString = arr.toString()
    getList()
  }
}
function tableRowClassName(row) {
  if (row.row.nextGroups) {
    return 'bg-color-EBEEF5'
  } else {
    return ''
  }
}
function arraySpanMethod({ row, column, rowIndex, columnIndex }) {
  if (row.nextGroups) {
    if (columnIndex === 0) {
      return {
        rowspan: 1,
        colspan: tableInfo.fieldList.length,
      }
    }
  }
}
</script>

<style scoped></style>
